<?php
namespace App\Http\Controllers\Admin;
/*
                   _ooOoo_ 
                  o8888888o 
                  88" . "88 
                  (| -_- |) 
                  O\  =  /O 
               ____/`---'\____ 
             .'  \\|     |//  `. 
            /  \\|||  :  |||//  \ 
           /  _||||| -:- |||||-  \ 
           |   | \\\  -  /// |   | 
           | \_|  ''\---/''  |   | 
           \  .-\__  `-`  ___/-. / 
         ___`. .'  /--.--\  `. . __ 
      ."" '<  `.___\_<|>_/___.'  >'"". 
     | | :  `- \`.;`\ _ /`;.`/ - ` : | | 
     \  \ `-.   \_ __\ /__ _/   .-` /  / 
======`-.____`-.___\_____/___.-`____.-'====== 
                   `=---=' 
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 
         佛祖保佑       永无BUG 
*/  
//          佛曰:
//                  写字楼里写字间，写字间里程序员；
//                  程序人员写程序，又拿程序换酒钱。
//                  酒醒只在网上坐，酒醉还来网下眠；
//                  酒醉酒醒日复日，网上网下年复年。
//                  但愿老死电脑间，不愿鞠躬老板前；
//                  奔驰宝马贵者趣，公交自行程序员。
//                  别人笑我忒疯癫，我笑自己命太贱；
//                  不见满街漂亮妹，哪个归得程序员？
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;
use App\Models\Tags;
use App\Models\Company;
use App\Models\TeachesCompany;
use App\Models\TeachesCompanyTags;
use App\Models\TeachesCompanyVideo;
use App\Models\TeachesCompanyOffice;
use App\Models\TeachesCompanyPpt;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
use App\User;

class TeachesCompanyController extends BaseController
{
    protected $catgory;
    protected $companys;
    
    /**
     * @see \App\Http\Controllers\Admin\BaseController::__construct()
     */
    public function __construct() {
        parent::__construct();
        $this->companys = Company::where('is_teaches','=',1)->orderBy('teaches_at','desc')->orderBy('created_at','desc')->orderBy('id','desc')->get();
    }
    
    /**
     * Show the application dashboard to the user.
     *
     * @return Response
     */
    public function index(Request $req)
    {
        if(!$this->user->can('viewTeachesCompany')) abort(405);

        $title = $req->input('title');
        $username = $req->input('author');
        $companyname = $req->input('companyname');

        $query = TeachesCompany::whereIn('is_validate',[1,2]);
        if(!empty($title))
        {
            $query->where('name','like','%'.$title.'%');
        }
        if(!empty($username))
        {
            $authorids = User::where('name','like','%'.$username.'%')->lists('id');
            $query->whereIn('user_id',$authorids);
        }

        if(!empty($companyname))
        {
            $companyids = Company::where('name','like','%'.$companyname.'%')->lists('id');
            $query->whereIn('company_id',$companyids);
        }
        $teaches = $query->orderBy("updated_at","desc")->paginate(20);
    
        return view('admin.teaches.company.index')->with('teaches',$teaches)
               ->with('title',$title)->with('username',$username)->with('companyname',$companyname);
    }
    
    /**
     * 充电加油待审核列表
     */
    public function noverify(Request $req)
    {
        if(!$this->user->can('viewTeachesCompany')) abort(405);
        
        $teaches = TeachesCompany::where('is_validate',0)->orderBy("updated_at","desc")->paginate(20);
        
        return view('admin.teaches.company.noverify')->with('teaches',$teaches);
    }
    
    
    /**
     *
     * @param  $id 新闻编号   经验文章
     */
    public function edit($id)
    {
        if(!$this->user->can('editTeachesCompany')) abort(405);
        
        $categorys=array();
        
        $result = TeachesCompany::find($id);
        if(empty($result))
        {
            abort(404);
        }
        $newsTag = array();
        foreach ($result->tags as $tag)
        {
            $newsTag[] = Tags::where('tags_id','=',$tag->tags_id)->first()->tags_name;
        }
        switch ($result->teaches_type)
        {
            case 1:
                $video = $result->video;
                
                return  view('admin.teaches.company.video')
                        ->with('type',$this->catgory)
                        ->with('result',$result)
                        ->with('categorys',$categorys)
                        ->with('videos',$video)
                        ->with('newstag',implode(",", $newsTag))
                        ->with('companys',$this->companys)
                        ->with('item',$this->item);
            case 2:
                $office = $result->office;
                
                return  view('admin.teaches.company.office')
                        ->with('type',$this->catgory)
                        ->with('result',$result)
                        ->with('categorys',$categorys)
                        ->with('office',$office)
                        ->with('newstag',implode(",", $newsTag))
                        ->with('companys',$this->companys)
                        ->with('item',$this->item);
            case 3:
                $office = $result->ppt;
                
                return  view('admin.teaches.company.ppt')
                ->with('type',$this->catgory)
                ->with('result',$result)
                ->with('categorys',$categorys)
                ->with('office',$office)
                ->with('newstag',implode(",", $newsTag))
                ->with('companys',$this->companys)
                ->with('item',$this->item);
                break;
            default:
                $result->description =collect(unserialize($result->description));
                $result->content = unserialize($result->content);
                $result->notice = collect(unserialize($result->notice));
                $result->tools = collect(unserialize($result->tools));
                
                return  view('admin.teaches.company.step')
                        ->with('type',$this->catgory)
                        ->with('result',$result)
                        ->with('categorys',$categorys)
                        ->with('newstag',implode(",", $newsTag))
                        ->with('companys',$this->companys)
                        ->with('item',$this->item);
        }
        
    }

    /**
     * 用于审核  
     * 文章详情展示
     */
    public function show($id)
    {
        if(!$this->user->can('viewTeachesCompany')) return $this->formatJson('error',$this->permerror);
        
        $newsTag = array();
        
        $result = TeachesCompany::find($id);
        if(empty($result))
        {
            return $this->formatJson('false');
        }
        
        foreach ($result->tags as $tag)
        {
            $newsTag[] = Tags::where('tags_id','=',$tag->tags_id)->first()->tags_name;
        }
        $result->username = $result->userinfo->name;
        $result->nowcate = "";
        $result->parentcate = "";
        $result->topcate = "";
        $result->newsTag = $newsTag;
        $result->companyname = $result->company->name;
        switch ($result->teaches_type)
        {
            case 1:
                $result->teachesVideo = $result->video?:"";
                break;
            case 2:
                $result->teachesOffice = $result->office?:"";
                break;
            case 3:
                $result->teachesPpt = $result->ppt?:"";
                break;
            default:
                $result->description =collect(unserialize($result->description));
                $result->content = collect(unserialize($result->content));
                $result->notice = collect(unserialize($result->notice));
                $result->tools = collect(unserialize($result->tools));
        }
        return $this->formatJson('success','获取数据成功！',$result);
    }
    
    /**
     * 新增  经验文章
     */
    public function create(Request $req)
    {
        if(!$this->user->can('editTeachesCompany')) return $this->formatJson('error',$this->permerror);
        
        $mod = $req->get('mod','step');
        if($mod === 'step' || empty($mod))
        {
            $path = 'admin.teaches.company.step';
        }
        elseif($mod === 'video')
        {
            $path = 'admin.teaches.company.video';
        }
        elseif($mod === 'office')
        {
            $path = 'admin.teaches.company.office';
        }
        elseif($mod === 'ppt')
        {
            $path = 'admin.teaches.company.ppt';
        }
        
        if(!$this->user->can('editTeaches')) abort(403);
        
        return  view($path)->with('type',$this->catgory)->with('companys',$this->companys);
    }
    
    /**
     * 保存数据  
     * @param teachesType 充电加油文章类型：0 经验文章；1 ：视频文章 2:office文章 默认 0
     * @param $req 请求参数
     */
    public function store(Request $req)
    {
        if(!$this->user->can('editTeachesCompany')) 
            return $this->formatJson('error',$this->permerror);
            
        $content = array();
       
        $data = $req->only('tcompanyid','name','description','descimg','tools','content','notice','tagsinput','author','from',
            'user_id','teachesType','sort','videoid','officeid','thumb','is_recommond','company_id');
        
        if(empty($data['company_id']))
        {
            return Response::json(array('status'=>'false','msg'=>'企业不能为空，请选择企业！'));
        }
        $company = Company::find($data['company_id']);
        if(empty($company))
            return $this->formatJson('error','企业不存在！');
        switch ($data['teachesType']){
            case 1: //视频文章
                $description = $data['description'];
                $contents = '视频教程';
                $tools = '';
                $notice = '';
                $video_id = $data['videoid'];
                break;
            case 2: //office 类系
                $description = $data['description'];
                $contents = 'office 类系教程';
                $tools = '';
                $notice = '';
                $office_id = $data['officeid'];
                break;
            case 3: //office 类系
                $description = $data['description'];
                $contents = 'ppt 类系教程';
                $tools = '';
                $notice = '';
                $office_id = $data['officeid'];
                break;
            default:
                $description = serialize(array('name'=>$data['description'],'img'=>strToArray($data['descimg'],",")));
                $tools = serialize($data['tools']);
                $content = stepContent($data['content']);                
                $contents = serialize($content);
                $notice = serialize($data['notice']);
        }
        
         $tagids = array();
         $tags = strToArray($data['tagsinput'], ",");
         foreach ($tags as $tg){
             if(!empty(trim($tg)))
             {
                 $tagsModel = Tags::firstOrCreate(['tags_name'=>trim($tg)]);
                 $tagids[] = $tagsModel->tags_id;
             }
         }
        $insert_row = array(
            'name'          =>   $data['name'],
            'cat_id'        =>   0,
            'thumb'         =>   $data['thumb'],
            'description'   =>   $description,
            'notice'        =>   $notice,
            'tools'         =>   $tools,
            'content'       =>   $contents,
            'author'        =>   $data['author'],
            'from'          =>   $data['from'],
            'sort'          =>   $data['sort'],
            'teaches_type'  =>   $data['teachesType'],
            'is_recommond'  =>   $data['is_recommond'],
            'company_id'    =>   $data['company_id']
        );
        if($data['tcompanyid'] > 0 && is_numeric($data['tcompanyid']))
        {
            $teaches = TeachesCompany::find($data['tcompanyid']);
            $insert_row['teaches_type'] = $teaches->teaches_type;
//             $insert_row['is_validate'] = $data['is_validate'];
//             if($insert_row['is_validate'] != 0)
//                 $insert_row['validated_at'] = date('Y-m-d H:i:s');
            foreach ($insert_row as $key=>$val)
            {
                $teaches->$key = $val;    
            }
            $teaches->save();
        }
        else
        {
            $insert_row['user_id']       = $this->user->id;
            $insert_row['is_validate']   =   1;
            $insert_row['validated_at']  =   date('Y-m-d H:i:s');
            $teaches = TeachesCompany::firstOrCreate($insert_row);
            $company->incrementAdd('teaches_count',1);
        }
        //建立关联 文章与标签
        TeachesCompanyTags::where('teaches_id','=',$teaches->id)->delete();
        foreach ($tagids as $tgd){
            TeachesCompanyTags::firstOrCreate(['tags_id'=>$tgd,'teaches_id'=>$teaches->id]);
        }
        switch ($data['teachesType'])
        {
            case 1:
                if(count($teaches->video)>0)
                {
                    $oldVideoId = $teaches->video->id;
                    if($oldVideoId != $video_id)
                    {
                        $video = TeachesCompanyVideo::find($video_id);
                        if(!empty($video))
                        {
                            $video->tcompany_id = $teaches->id;
                            TeachesCompanyVideo::where('id','=',$oldVideoId)->delete();
                            $video->save();
                        }
                    }
                }
                else 
                {
                    $video = TeachesCompanyVideo::find($video_id);
                    if(!empty($video))
                    {
                        $video->tcompany_id = $teaches->id;
                        $video->save();
                    }
                }
                break;
            case 2:
                if(count($teaches->office)>0)
                {
                    $oldOfficeId = $teaches->office->id;
                    if($oldOfficeId != $office_id)
                    {
                        $ppt=TeachesCompanyOffice::find($office_id);
                        if(!empty($ppt))
                        {
                            $ppt->tcompany_id = $teaches->id;
                            TeachesCompanyOffice::where("id",'=',$oldOfficeId)->delete();
                            $ppt->save();
                        }
                    }
                }
                else
                {
                    $ppt=TeachesCompanyOffice::find($office_id);
                    if(!empty($ppt))
                    {
                        $ppt->tcompany_id = $teaches->id;
                        $ppt->save();
                    }
                }
                break;
            case 3:
                if(count($teaches->ppt)>0)
                {
                    $oldOfficeId = $teaches->ppt->id;
                    if($oldOfficeId != $office_id)
                    {
                        $ppt=TeachesCompanyPpt::find($office_id);
                        if(!empty($ppt))
                        {
                            $ppt->tcompany_id = $teaches->id;
                            TeachesCompanyPpt::where("id",'=',$oldOfficeId)->delete();
                            $ppt->save();
                        }
                    }
                }
                else
                {
                    $ppt=TeachesCompanyPpt::find($office_id);
                    if(!empty($ppt))
                    {
                        $ppt->tcompany_id = $teaches->id;
                        $ppt->save();
                    }
                }
                break;
        }
        return Response::json(array('id'=>$teaches->id,'status'=>'success','msg'=>'保存数据成功！','redirectUrl'=>'/admin/teaches/enterprise'));
    }
    
    /**
     * 文章审核
     * @param Request $req
     */
    public function teachesValidate(Request $req)
    {
        if(!$this->user->can('editTeachesCompany')) 
            return $this->formatJson('error',$this->permerror);
        
        $data = $req->only('is_validate','id');
        if(empty($data['is_validate']))
        {
            return $this->formatJson('error','请选择审核结果！');
        }
        $teaches = TeachesCompany::find($data['id']);
        $teaches->is_validate = $data['is_validate'];
        $teaches->validated();
        if($teaches->is_validate == 1)
            return $this->formatJson('success',"文章：［ ".$teaches->name." ］审核通过！",$teaches,'/admin/teaches/enterprise');
        else if($teaches->is_validate == 2)
            return $this->formatJson('success',"文章：［ ".$teaches->name." ］不通过！",$teaches,'/admin/teaches/enterprise');
    }
    
    /**
     * 删除
     */
    public function destroy($news_id)
    {
        if(!$this->user->can('delteTeachesCompany'))
            return $this->formatJson('error',$this->permerror);
        
        $news = TeachesCompany::find($news_id);
        $company = Company::find($news->company_id);
        DB::beginTransaction();
        try{
            if($company)
                $company->decrementDel('teaches_count',1);
            $news->delete();
            DB::commit();
        }catch (\PDOException $e){
            Log::info(['删除企业内训异常'=>$e->getMessage()]);
            DB::rollBack();
            return $this->formatJson('error','删除失败！');
        }
        return  Response::json(array('status'=>'success','msg'=>'文章：［'.$news->name.'］ 删除成功'));
    }
    
    
    /**
     * 首页推荐 0 不推荐  1 推荐
     */
    public function recommond(Request $request)
    {
        if(!$this->user->can('editTeachesCompany'))
            return $this->formatJson('error',$this->permerror);
        
        $id = $request->input('id');
        $is_recommond = $request->input('is_disabled');
        $teaches = TeachesCompany::find($id);
        
        $teaches->is_recommond = $is_recommond = $is_recommond > 0 ? 0 : 1;
        if ($teaches->save())
            return  Response::json(array('status'=>'success','msg'=>'广告位', 'data' => $is_recommond));
    }
    
}
